package com.ec.pf.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ec.api.client.UserClient;
import com.ec.common.domain.Result;
import com.ec.common.exception.BadRequestException;
import com.ec.pf.mapper.FamilyProfileMapper;
import com.ec.pf.pojo.FamilyProfile;
import com.ec.pf.service.FamilyProfileService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class FamilyProfileServiceImpl extends ServiceImpl<FamilyProfileMapper, FamilyProfile> implements FamilyProfileService {

    private final FamilyProfileMapper familyProfileMapper;
    private final UserClient userClient;

    @Override
    public FamilyProfile addFamilyProfile(FamilyProfile familyProfile) {
        // 验证 user_id 是否存在
        Result<Boolean> existsResult = userClient.checkUserExists(familyProfile.getUserId());
        if (!existsResult.getData()) {
            throw new BadRequestException("用户ID不存在");
        }
        familyProfileMapper.insert(familyProfile);
        return familyProfile;
    }

    @Override
    public boolean deleteFamilyProfileById(Long id) {
        return familyProfileMapper.deleteById(id) > 0;
    }

    @Override
    public FamilyProfile updateFamilyProfile(FamilyProfile familyProfile) {
        familyProfileMapper.updateById(familyProfile);
        return familyProfile;
    }

    @Override
    public FamilyProfile getFamilyProfileById(Long id) {
        return familyProfileMapper.selectById(id);
    }

    @Override
    public Page<FamilyProfile> listFamilyProfiles(Integer page, Integer size) {
        Page<FamilyProfile> familyProfilePage = new Page<>(page, size);
        return familyProfileMapper.selectPage(familyProfilePage, null);
    }

    @Override
    public boolean batchDeleteFamilyProfiles(List<Long> ids) {
        return familyProfileMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Page<FamilyProfile> searchFamilyProfiles(String fullName, String gender, String phone, int page, int size) {
        Page<FamilyProfile> familyProfilePage = new Page<>(page, size);
        QueryWrapper<FamilyProfile> queryWrapper = new QueryWrapper<>();

        // 按姓名进行模糊查询
        if (fullName != null && !fullName.isEmpty()) {
            queryWrapper.like("full_name", fullName);
        }

        // 按性别进行模糊查询
        if (gender != null && !gender.isEmpty()) {
            queryWrapper.like("gender", gender);
        }

        // 按电话进行模糊查询
        if (phone != null && !phone.isEmpty()) {
            queryWrapper.like("phone", phone);
        }

        return this.page(familyProfilePage, queryWrapper);
    }

}
